package com.oktago.ibore;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.json.JSONArray;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class ListActivity extends Activity {

    private Handler myHandler;
    private ProgressDialog progressDialog;
    private final static int WAITING_PROGRESS_DIALOG_ID = 1;
    private final static int ITEMS_PER_PAGE = 20;
    private final static int DOWNLOAD_COUNT = 0, DOWNLOAD_PAGE = 1;
    private int status = DOWNLOAD_COUNT;
    private long idt;
    private Long root;
    private String jsonString;
    private int currentPage;
    private int lastPage;
    ObjectListAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);
        adapter = new ObjectListAdapter(this);
        Intent received = getIntent();
        Bundle argument = received.getExtras();
        idt = argument.getLong("idt");
        if (argument.containsKey("root")) {
            root= argument.getLong("root");
        }

        ListView lv = (ListView) findViewById(R.id.ListPublication);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(adapter);
        myHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.obj.toString().equals("")) {
                    ListView lv = (ListView) findViewById(R.id.ListPublication);
                    lv.setVisibility(View.GONE);
                    dismissDialog(WAITING_PROGRESS_DIALOG_ID);
                    return;
                }
                if (status == DOWNLOAD_COUNT) {
                    int totItems = Integer.parseInt(msg.obj.toString().replace("\"", ""));
                    lastPage = (int) Math.ceil(1.0 * totItems / ITEMS_PER_PAGE);
                    status = DOWNLOAD_PAGE;
                    currentPage = 1;
                    IBoreApplication iBoreApplication = (IBoreApplication) getApplication();
                    try {
                        iBoreApplication.downloadList(idt, root, 1, ITEMS_PER_PAGE, myResponseHandler);
                    } catch (URISyntaxException ex) {
                        Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    return;
                }

                if (status == DOWNLOAD_PAGE) {
                    jsonString = msg.obj.toString();
                    try {
                        //Visualizziamo i Risultati e stoppiamo la Dialog
                        adapter.updateDataSet(new JSONArray(jsonString));
                        adapter.notifyDataSetChanged();
                        //visualizzaItems();
                        //dismissDialog(WAITING_PROGRESS_DIALOG_ID);
                        ImageButton rew = (ImageButton) findViewById(R.id.ImageButtonRew);
                        if (currentPage == 1) {
                            rew.setEnabled(false);
                        } else {
                            rew.setEnabled(true);
                        }
                        ImageButton ff = (ImageButton) findViewById(R.id.ImageButtonFF);
                        if (currentPage == lastPage) {
                            ff.setEnabled(false);
                        } else {
                            ff.setEnabled(true);
                        }
                        TextView pageTv = (TextView) findViewById(R.id.TextViewPage);
                        pageTv.setTextSize(20);
                        pageTv.setText(currentPage + "/" + lastPage);
                        pageTv.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        final ImageButton ff = (ImageButton) findViewById(R.id.ImageButtonFF);
        final ImageButton rew = (ImageButton) findViewById(R.id.ImageButtonRew);


        ff.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (currentPage<lastPage) {
                    currentPage++;
                    IBoreApplication iBoreApplication = (IBoreApplication) getApplication();
                    try {
                        iBoreApplication.downloadList(idt, root, currentPage, ITEMS_PER_PAGE, myResponseHandler);
                    } catch (URISyntaxException ex) {
                        Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });

        rew.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (currentPage>1) {
                    currentPage--;
                    IBoreApplication iBoreApplication = (IBoreApplication) getApplication();
                    try {
                        iBoreApplication.downloadList(idt, root, currentPage, ITEMS_PER_PAGE, myResponseHandler);
                    } catch (URISyntaxException ex) {
                        Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        });


        //Operazioni d'avvio

        IBoreApplication app = (IBoreApplication) getApplication();
        try {
            app.countInstances(idt, root, myResponseHandler);
        } catch (URISyntaxException ex) {
            Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ListActivity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case WAITING_PROGRESS_DIALOG_ID:
                progressDialog = new ProgressDialog(this,
                        ProgressDialog.STYLE_SPINNER);
                progressDialog.setTitle("HTTP Connection");
                progressDialog.setMessage("Connecting...");
                progressDialog.setIndeterminate(true);
                return progressDialog;
            default:
                return null;
        }
    }

    public void showMessageOnOutput(String result) {
        Message msg = myHandler.obtainMessage();
        msg.obj = result;
        myHandler.sendMessage(msg);
    }
    private final ResponseHandler<String> myResponseHandler = new ResponseHandler<String>() {

        public String handleResponse(HttpResponse response)
                throws ClientProtocolException, IOException {
            // Estraiamo il risultato dalla risposta. Otteniamo quindi il content
            // da cui leggere le informazioni
            InputStream content = response.getEntity().getContent();
            byte[] buffer = new byte[1024];
            int numRead = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((numRead = content.read(buffer)) != -1) {
                baos.write(buffer, 0, numRead);
            }
            // Chiudiamo lo stream
            content.close();
            // Otteniamo il risultato
            String result = new String(baos.toByteArray());
            showMessageOnOutput(result);

            return result;
        }
    };

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //outState.putInt("currentPage", currentPage);
    }
}
